package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.equipment.assessment.dto.InspectSelfTreeTableDTO;
import com.sduept.bigdata.equipment.assessment.enums.InspectionType;
import com.sduept.bigdata.equipment.assessment.enums.SubStationTypeEnum;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionItem;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.bigdata.equipment.assessment.service.InspectionItemService;
import com.sduept.bigdata.equipment.assessment.service.InspectionPlanService;
import com.sduept.bigdata.equipment.assessment.service.InspectionStationService;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.permission.entity.PersonnelEntityBean;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;
/**
 * 新建、编辑自查计划控制器
 * @author pengz
 *
 */
@Named
@ViewScoped
public class AddOrEditInspectSelfPlanController extends AbstractController{

	private static final long serialVersionUID = 7825215644877551081L;
	@Autowired
	private InspectionPlanService planService;
	@Autowired
	private InspectionStationService stationService;
	@Autowired
	private InspectionItemService itemService;
	/**
	 * 传入的参数：计划id
	 */
	private String planId;
	/**
	 * 目标计划
	 */
	private InspectionPlan targetPlan;
	/**
	 * 评价厂站根节点
	 */
	private TreeNode root;
	/**
	 * 选中的节点
	 */
	private TreeNode[] selectedNodes;
	/**
	 * 评价厂站树的一级节点（检修范围）
	 */
//	private Map<String,TreeNode> scopeNameToFirstLevelNodeMap;
	/**
	 * 评价厂站树的二级节点（运维单位）
	 */
//	private Map<String,TreeNode> unitNameToSecondLevelNodeMap;
	/**
	 * 新建的评价厂站
	 */
	private Map<String,InspectionStation> waitToSaveMap;
	private Map<String,InspectionStation> allMap;
	
	private TreeNode selectedSecondNode;
	/**
	 * 变电站联系人信息
	 */
	private String stationPersonnel;
	private String stationPersonnelPhone;
	
	private TreeNode selectedFirstNode;
	/**
	 * 中调联系人信息
	 */
	private String inspectionScopePersonnel;
	private String inspectionScopePersonnelPhone;
	{
		root = new DefaultTreeNode();
//		scopeNameToFirstLevelNodeMap = new HashMap<String, TreeNode>();
//		unitNameToSecondLevelNodeMap = new HashMap<String, TreeNode>();
		waitToSaveMap = new HashMap<String, InspectionStation>();
		allMap = new HashMap<String, InspectionStation>();
	}
	@PostConstruct
	public void init() {
		initParamter();
		initTargetPlan();
	}
	/**
	 * 初始化参数信息
	 */
	private void initParamter() {
		planId = getParameter("id");
	}
	/**
	 * 初始化targetPlan
	 */
	private void initTargetPlan() {
		if(StringUtils.isNotBlank(planId)) {
			targetPlan = planService.findById(planId);
			try {
				Set<InspectionStation> currentInstations = stationService.findByInspectionPlan(planId);
				generateTreeNodeFromInspectionStations(new ArrayList<InspectionStation>(currentInstations),true);
			} catch (ParameterException e) {
				e.printStackTrace();
			}
		}else {
			targetPlan = new InspectionPlan();
			//评价类型：互查
			targetPlan.setInspectionType(InspectionType.INSPECTIONSELF);
			//创建人：当前用户
			targetPlan.setCreator(getCurrentUser().getName());
		}
	}
	/**
	 * 初始化评价厂站信息树根节点
	 * @param inspectionStations
	 */
	private void generateTreeNodeFromInspectionStations(List<InspectionStation> inspectionStations,boolean fromDB) {
		Map<String,TreeNode> scopeNameToFirstLevelNodeMap = new HashMap<String, TreeNode>();
		Map<String,TreeNode> unitNameToSecondLevelNodeMap = new HashMap<String, TreeNode>();
		for(InspectionStation instation : inspectionStations) {
			allMap.put(instation.getId(), instation);
			String scopeKey = instation.getAcceptScope()+"-"+instation.getInspectionScopePersonnel()+"-"+instation.getInspectionScopePersonnelPhone();
			if(!scopeNameToFirstLevelNodeMap.containsKey(scopeKey)) {
				InspectSelfTreeTableDTO firstLevelModel = new InspectSelfTreeTableDTO();
				firstLevelModel.setType("first");
				firstLevelModel.setName(instation.getAcceptScope());
				firstLevelModel.setInspectionScopePersonnel(instation.getInspectionScopePersonnel());
				firstLevelModel.setInspectionScopePersonnelPhone(instation.getInspectionScopePersonnelPhone());
				TreeNode firstLevelNode = new DefaultTreeNode(firstLevelModel.getType(),firstLevelModel,root);
				scopeNameToFirstLevelNodeMap.put(scopeKey, firstLevelNode);
			}
			String unitKey = instation.getAcceptScope()+"-"+instation.getAcceptUnit()+"-"+instation.getStationPersonnel()+"-"+instation.getStationPersonnelPhone();
			if(!unitNameToSecondLevelNodeMap.containsKey(unitKey)) {
				InspectSelfTreeTableDTO secondLevelModel = new InspectSelfTreeTableDTO();
				secondLevelModel.setType("second");
				secondLevelModel.setName(instation.getAcceptUnit());
				secondLevelModel.setStationPersonnel(instation.getStationPersonnel());
				secondLevelModel.setStationPersonnelPhone(instation.getStationPersonnelPhone());
				TreeNode secondLevelNode = new DefaultTreeNode(secondLevelModel.getType(),secondLevelModel,scopeNameToFirstLevelNodeMap.get(scopeKey));
				unitNameToSecondLevelNodeMap.put(unitKey, secondLevelNode);
			}
			InspectSelfTreeTableDTO thirdLevelModel = new InspectSelfTreeTableDTO();
			thirdLevelModel.setType("third");
			thirdLevelModel.setName(instation.getStationName());
			thirdLevelModel.setInspectExpert(instation.getInspectionExpert());
			thirdLevelModel.setInspectionUnit(instation.getInspectionUnit());
			thirdLevelModel.setStationType(instation.getStationType().getLabel());
			thirdLevelModel.setStationPersonnel(instation.getStationPersonnel());
			thirdLevelModel.setStationPersonnelPhone(instation.getStationPersonnelPhone());
			thirdLevelModel.setInspectExpertPhone(instation.getInspectionExpertPhone());
			thirdLevelModel.setStartTime(instation.getStartTime());
			thirdLevelModel.setEndTime(instation.getEndTime());
			if(fromDB) {
				thirdLevelModel.setFromDB(true);
			}
			thirdLevelModel.setInspectionStationId(instation.getId());
			new DefaultTreeNode(thirdLevelModel.getType(),thirdLevelModel,unitNameToSecondLevelNodeMap.get(unitKey));
		}
	}
	/**
	 * 组织机构人员选择器弹窗返回处理函数
	 */
	public void onUserDialogReturn() {
		String userJson = getParameter("userJson");
		String className = getParameter("className");
		if(PersonnelEntityBean.class.getSimpleName().equals(className) && StringUtils.isNoneBlank(userJson) ){
			PersonnelEntityBean user = JSONObject.parseObject(userJson, PersonnelEntityBean.class);
			targetPlan.setResponsible(user.getName());
    	}
	}
	/**
	 * 添加评价厂站弹窗关闭返回处理函数
	 */
	public void onAddInspectionStationSelectorDialogReturn() {
//		String stationType = getParameter("stationType");
		String selectedInspectionStationStr = getParameter("selectedInspectionStations");
		List<InspectionStation> selectedInspsectionStations = JSONArray.parseArray(selectedInspectionStationStr, InspectionStation.class);
		if(selectedInspsectionStations!=null) {
			for(InspectionStation instation : selectedInspsectionStations) {
				instation.setId(ObjectId.get().toString());//标识
				//默认常规站
				SubStationTypeEnum type = SubStationTypeEnum.CONVENTIONAL;
//				for(SubStationTypeEnum substationType : SubStationTypeEnum.values()) {
//					if(substationType.name().equals(stationType)) {
//						type = substationType;
//					}
//				}
				instation.setStationType(type);
				waitToSaveMap.put(instation.getId(), instation);
			}
			generateTreeNodeFromInspectionStations(selectedInspsectionStations, false);
		}
		
	}
	/**
	 * 选择模板弹窗关闭返回处理函数
	 */
	public void onSelectFromTemplateDialogReturn() {
		String selectedInspectionStationStr = getParameter("selectedInspectionStations");
		List<InspectionStation> selectedInspsectionStations = JSONArray.parseArray(selectedInspectionStationStr, InspectionStation.class);
		for(InspectionStation instation : selectedInspsectionStations) {
//			List<InspectionItem> items = instation.getInspectionItems();
//			for(InspectionItem item : items) {
//				for(ItemTypeEnum type : ItemTypeEnum.values()) {
//					if(type.getValue().equals(item.getItemType().getValue())) {
//						item.setItemType(type);
//						break;
//					}
//				}
//			}
			instation.setId(ObjectId.get().toString());
			waitToSaveMap.put(instation.getId(), instation);
			allMap.put(instation.getId(), instation);
		}
		generateTreeNodeFromInspectionStations(selectedInspsectionStations, false);
	}
	/**
	 * 删除按钮是否可用
	 * @return
	 */
	public boolean disabledDelBtn() {
		if(selectedNodes==null||selectedNodes.length<=0) {
			return true;
		}
		return false;
	}
	/**
	 * 删除选中的节点
	 */
	public void deleteSelectedNodes() {
		List<String> deleteStations = new ArrayList<String>();
		for(int i=0;i<selectedNodes.length;i++) {
			TreeNode selectedNode = selectedNodes[i];
			selectedNode.getParent().getChildren().remove(selectedNode);
			if(selectedNode.getType().equals("third")) {
				InspectSelfTreeTableDTO thirdLevelModel = (InspectSelfTreeTableDTO) selectedNode.getData();
				if(thirdLevelModel.isFromDB()) {//从数据库中删除
					deleteStations.add(thirdLevelModel.getInspectionStationId());
				}else {
					if(waitToSaveMap.containsKey(thirdLevelModel.getInspectionStationId())) {
						waitToSaveMap.remove(thirdLevelModel.getInspectionStationId());
					}
				}
				if(allMap.containsKey(thirdLevelModel.getInspectionStationId())) {
					allMap.remove(thirdLevelModel.getInspectionStationId());
				}
			}
		}
		addSuccessMessage("删除成功！");
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(String stationId : deleteStations) {
					try {
						stationService.deleteById(stationId);
					} catch (ParameterException e) {
						e.printStackTrace();
					}
				}
				
			}
		}).start();
		selectedNodes = null;
	}

	/**
	 * 保存草稿
	 */
	public void saveAssessmentPlan() {
		if(saveIsAvailable()) {
			//1.保存计划
			if(StringUtils.isEmpty(planId)) {//新建计划时
				targetPlan.setCreateTime(new Date());
				targetPlan.setStatus(0);
			}
			InspectionPlan inspectionPlan = planService.createOrupdate(targetPlan);
			//2.保存评价厂站
			List<InspectionStation> inspectionStations = new ArrayList<InspectionStation>();
			for(String id : waitToSaveMap.keySet()) {
				InspectionStation instation = waitToSaveMap.get(id);
				instation.setInspectPlan(inspectionPlan);
//				instation.setStartTime(inspectionPlan.getStartTime());
//				instation.setEndTime(inspectionPlan.getEndTime());
				instation.setInspectionItems(null);
				InspectionStation inspectionStation = stationService.create(instation);
				inspectionStations.add(inspectionStation);
				//3.生成检查条目
//				if(inspectionStation.getStationType()!=null) {
//					try {
//						itemService.generateStationInspectionItems(inspectionStation.getStationType(), inspectionStation.getId());
//					} catch (ParameterException e) {
//						e.printStackTrace();
//					}
//				}
			}
			//3.生成检查条目
			//另开一个线程保存评价项
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					for(InspectionStation instation : inspectionStations) {
						if(instation.getStationType()!=null) {
							try {
								itemService.generateStationInspectionItems(instation.getStationType(), instation.getId());
							} catch (ParameterException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}).start();
//			for(InspectionStation instation : inspectionStations) {
//				if(instation.getStationType()!=null) {
//					try {
//						itemService.generateStationInspectionItems(instation.getStationType(), instation.getId());
//					} catch (ParameterException e) {
//						e.printStackTrace();
//					}
//				}
//			}
			//关闭弹窗并返回数据
			JSONObject r = new JSONObject();
			r.put("inspectionPlanId", inspectionPlan.getId());
			PrimeFaces.current().executeScript("closeAndSave("+r.toJSONString()+")");
		}
	}
	/**
	 * 判断是否可用保存计划为草稿
	 * 可以保存的条件：
	 * 1.计划基本信息完整：评价名称、评价时间、负责人已填写
	 * @return
	 */
	private boolean saveIsAvailable() {
		if(StringUtils.isBlank(targetPlan.getName())) {
			alertErrorMessage("请填写该计划名称！");
			return false;
		}
//		if(targetPlan.getStartTime()==null||targetPlan.getEndTime()==null) {
//			alertErrorMessage("请完善评价计划时间！");
//			return false;
//		}
		if(StringUtils.isBlank(targetPlan.getResponsible())) {
			alertErrorMessage("请选择负责人！");
			return false;
		}
		return true;
	}
	
	public List<String> completeStationTypes() {
		List<String> result = new ArrayList<String>();
		for(SubStationTypeEnum stationType : SubStationTypeEnum.values()) {
			result.add(stationType.getLabel());
		}
		return result;
	}
	/**
	 * 选择抽检类型
	 * @param model
	 */
	public void onStationTypeChanged(InspectSelfTreeTableDTO model) {
		if(allMap.containsKey(model.getInspectionStationId())) {
			InspectionStation instation = allMap.get(model.getInspectionStationId());
			for(SubStationTypeEnum stationType : SubStationTypeEnum.values()) {
				if(stationType.getLabel().equals(model.getStationType())) {
					instation.setStationType(stationType);
					if(model.isFromDB()) {
						//删除历史数据
						List<InspectionItem> items = itemService.findBySubId(instation.getId());
						for(InspectionItem item : items) {
							itemService.deleteById(item.getId());
						}
						//重新生成
						try {
							itemService.generateStationInspectionItems(instation.getStationType(), instation.getId());
						} catch (ParameterException e) {

							e.printStackTrace();
						}
					}
					break;
				}
			}
		}
	}
	/**
	 * 添加派出专家
	 * @param model
	 */
	public void onInspectExpertBlur(InspectSelfTreeTableDTO model) {
		if(allMap.containsKey(model.getInspectionStationId())) {
			InspectionStation instation = allMap.get(model.getInspectionStationId());
			instation.setInspectionExpert(model.getInspectExpert());
			if(model.isFromDB()) {
				stationService.create(instation);
			}
		}
	}
	/**
	 * 添加派出专家联系电话
	 * @param model
	 */
	public void onInspectExpertPhoneBlur(InspectSelfTreeTableDTO model) {
		if(allMap.containsKey(model.getInspectionStationId())) {
			InspectionStation instation = allMap.get(model.getInspectionStationId());
			instation.setInspectionExpertPhone(model.getInspectExpertPhone());
			if(model.isFromDB()) {
				stationService.create(instation);
			}
		}
	}
	/**
	 * 选择开始时间
	 * @param model
	 */
	public void onStartDataSelect(InspectSelfTreeTableDTO model) {
		if(allMap.containsKey(model.getInspectionStationId())) {
			InspectionStation instation = allMap.get(model.getInspectionStationId());
			instation.setStartTime(model.getStartTime());
			if(model.isFromDB()) {
				stationService.create(instation);
			}
		}
	}
	/**
	 * 选择结束时间
	 * @param model
	 */
	public void onEndDataSelect(InspectSelfTreeTableDTO model) {
		if(allMap.containsKey(model.getInspectionStationId())) {
			InspectionStation instation = allMap.get(model.getInspectionStationId());
			instation.setEndTime(model.getEndTime());
			if(model.isFromDB()) {
				stationService.create(instation);
			}
		}
	}
	/**
	 * 添加派出专家供电局
	 * @param model
	 */
	public void onInspectionUnitBlur(InspectSelfTreeTableDTO model) {
		if(allMap.containsKey(model.getInspectionStationId())) {
			InspectionStation instation = allMap.get(model.getInspectionStationId());
			instation.setInspectionUnit(model.getInspectionUnit());
			if(model.isFromDB()) {
				stationService.create(instation);
			}
		}
	}
	/**
	 * 设置当前操作的二级节点（供电局）
	 * @param node
	 */
	public void setSelectedSecondNode(TreeNode node) {
		this.selectedSecondNode = node;
		InspectSelfTreeTableDTO model = (InspectSelfTreeTableDTO) this.selectedSecondNode.getData();
		this.stationPersonnel = model.getStationPersonnel();
		this.stationPersonnelPhone = model.getStationPersonnelPhone();
	}
	
	public void saveOrUpdateStationPersonnalInfo() {
		InspectSelfTreeTableDTO model = (InspectSelfTreeTableDTO) this.selectedSecondNode.getData();
		model.setStationPersonnel(this.stationPersonnel);
		model.setStationPersonnelPhone(this.stationPersonnelPhone);
		List<TreeNode> children = this.selectedSecondNode.getChildren();
		for (TreeNode treeNode : children) {
			InspectSelfTreeTableDTO childData = (InspectSelfTreeTableDTO) treeNode.getData();
			childData.setStationPersonnel(this.stationPersonnel);
			childData.setStationPersonnelPhone(this.stationPersonnelPhone);
			if(allMap.containsKey(childData.getInspectionStationId())) {
				InspectionStation instation = allMap.get(childData.getInspectionStationId());
				instation.setStationPersonnel(this.stationPersonnel);
				instation.setStationPersonnelPhone(this.stationPersonnelPhone);
//				if(!waitToSaveMap.containsKey(instation.getId())) {
//					waitToSaveMap.put(instation.getId(), instation);
//				}
				if(childData.isFromDB()) {
					stationService.create(instation);
				}
			}
		}
	}
	/**
	 * 设置当前操作的一级节点（检修范围/中调）
	 * @param node
	 */
	public void setSelectedFirstNode(TreeNode node) {
		this.selectedFirstNode = node;
		InspectSelfTreeTableDTO model = (InspectSelfTreeTableDTO) this.selectedFirstNode.getData();
		this.inspectionScopePersonnel = model.getInspectionScopePersonnel();
		this.inspectionScopePersonnelPhone = model.getInspectionScopePersonnelPhone();
	}
	public void saveOrUpdateInspectionScopePersonnelInfo() {
		InspectSelfTreeTableDTO model = (InspectSelfTreeTableDTO) this.selectedFirstNode.getData();
		model.setInspectionScopePersonnel(this.inspectionScopePersonnel);
		model.setInspectionScopePersonnelPhone(this.inspectionScopePersonnelPhone);
		for(TreeNode secondNode : this.selectedFirstNode.getChildren()) {
			for(TreeNode thirdNode: secondNode.getChildren()) {
				InspectSelfTreeTableDTO thirdNodeData = (InspectSelfTreeTableDTO) thirdNode.getData();
				thirdNodeData.setInspectionScopePersonnel(this.inspectionScopePersonnel);
				thirdNodeData.setInspectionScopePersonnelPhone(this.inspectionScopePersonnelPhone);
				if(allMap.containsKey(thirdNodeData.getInspectionStationId())) {
					InspectionStation instation = allMap.get(thirdNodeData.getInspectionStationId());
					instation.setInspectionScopePersonnel(this.inspectionScopePersonnel);
					instation.setInspectionScopePersonnelPhone(this.inspectionScopePersonnelPhone);
					if(thirdNodeData.isFromDB()) {
						stationService.create(instation);
					}
				}
			}
		}
	}
	
	public InspectionPlan getTargetPlan() {
		return targetPlan;
	}
	public void setTargetPlan(InspectionPlan targetPlan) {
		this.targetPlan = targetPlan;
	}
	public TreeNode getRoot() {
		return root;
	}
	public void setRoot(TreeNode root) {
		this.root = root;
	}
	public TreeNode[] getSelectedNodes() {
		return selectedNodes;
	}
	public void setSelectedNodes(TreeNode[] selectedNodes) {
		this.selectedNodes = selectedNodes;
	}
	public String getStationPersonnel() {
		return stationPersonnel;
	}
	public void setStationPersonnel(String stationPersonnel) {
		this.stationPersonnel = stationPersonnel;
	}
	public String getStationPersonnelPhone() {
		return stationPersonnelPhone;
	}
	public void setStationPersonnelPhone(String stationPersonnelPhone) {
		this.stationPersonnelPhone = stationPersonnelPhone;
	}
	public String getInspectionScopePersonnel() {
		return inspectionScopePersonnel;
	}
	public void setInspectionScopePersonnel(String inspectionScopePersonnel) {
		this.inspectionScopePersonnel = inspectionScopePersonnel;
	}
	public String getInspectionScopePersonnelPhone() {
		return inspectionScopePersonnelPhone;
	}
	public void setInspectionScopePersonnelPhone(String inspectionScopePersonnelPhone) {
		this.inspectionScopePersonnelPhone = inspectionScopePersonnelPhone;
	}
	
}
